<template>
    <div class="modbus-model-management">
        <div class="table-operations">
            <a-button type="primary" @click="handleAdd">新建</a-button>
            <a-button @click="refreshList">刷新</a-button>
        </div>

        <a-table :columns="columns" :data-source="dataSource" :loading="loading" :pagination="pagination" row-key="id">
            <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'action'">
                    <a-space>
                        <a @click="handleEdit(record)">编辑</a>
                        <a @click="handleViewDataPoints(record)">数据点表</a>
                        <a-popconfirm title="确定要删除此模型吗？" @confirm="handleDelete(record)">
                            <a style="color: #ff4d4f">删除</a>
                        </a-popconfirm>
                    </a-space>
                </template>
            </template>
        </a-table>

        <!-- 新增/编辑模态框 -->
        <a-modal v-model:open="modalVisible" :title="modalTitle" @ok="handleModalOk" @cancel="resetForm"
            :confirm-loading="confirmLoading">
            <a-form ref="formRef" :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                <a-form-item label="模型名称" name="name" :rules="[{ required: true, message: '请输入模型名称' }]">
                    <a-input v-model:value="formState.name" placeholder="请输入模型名称" />
                </a-form-item>

                <a-form-item label="模型描述" name="dec" :rules="[{ required: true, message: '请输入模型描述' }]">
                    <a-input v-model:value="formState.dec" placeholder="请输入模型描述" />
                </a-form-item>

                <a-form-item label="组态模型" name="configUid">
                    <a-select v-model:value="formState.configUid" @change="changeConfigUid">
                        <a-select-option v-for="option in modelOptions" :key="option.ID" :value="option.displayUid">
                            {{ option.name }}
                        </a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item label="组态展示页面" name="PageUUID">
                    <a-select v-model:value="formState.PageUUID">
                        <a-select-option v-for="option in pageOptions" :key="option.PageId" :value="option.PageId">
                            {{ option.PageName }}
                        </a-select-option>
                    </a-select>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { cvaiApi } from '/@/api/system/cvai-api';

// 表格列定义
const columns = [
    {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        width: 80,
        customRender: ({ index }) => index + 1,
    },
    {
        title: '模型名称',
        dataIndex: 'name',
        key: 'name',
    },
    {
        title: '模型描述',
        dataIndex: 'dec',
        key: 'dec',
    },
    {
        title: '操作',
        key: 'action',
        width: 200,
    },
];

// 响应式数据
const dataSource = ref([]);
const loading = ref(false);
const modalVisible = ref(false);
const modalTitle = ref('新增模型');
const isEdit = ref(false);
const confirmLoading = ref(false);
const formRef = ref();
const currentModelId = ref(null);

// 表单状态
const formState = reactive({
    name: '',
    dec: '',
    type: 350,
    gatherNumber: 0,
    configUid: '',
    PageUUID: '',
});

// 分页配置
const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    pageSizeOptions: ['10', '20', '50'],
    onChange: (page, pageSize) => {
        pagination.current = page;
        pagination.pageSize = pageSize;
        fetchData();
    },
});

// 生命周期钩子
onMounted(() => {
    fetchData();
    getDisplayModelListOptions(); // 获取组态模型列表
});

// 获取模型列表
const fetchData = async () => {
    try {
        loading.value = true;
        cvaiApi.IEC61850ModelList({ type: 350 }).then((res) => {
            if (res.code === 0) {
                dataSource.value = res.list; // 将数据模型选项存储到 modelOptions 中
                pagination.total = res.list.length;
            }
        });
    } catch (error) {
        console.error('获取模型列表失败:', error);
        message.error('获取模型列表失败');
    } finally {
        loading.value = false;
    }
};

// 刷新列表
const refreshList = () => {
    pagination.current = 1;
    fetchData();
};

// 处理新增按钮
const handleAdd = () => {
    resetForm();
    modalTitle.value = '新增模型';
    isEdit.value = false;
    modalVisible.value = true;
};

// 处理编辑按钮
const handleEdit = (record) => {
    currentModelId.value = record.uuid;
    modalTitle.value = '编辑模型';
    isEdit.value = true;
    changeConfigUid(record.configUid);

    // 填充表单
    Object.assign(formState, {
        name: record.name,
        dec: record.dec,
        type: record.type || 350,
        gatherNumber: record.gatherNumber || 0,
        configUid: record.configUid,
        PageUUID: record.PageUUID,
    });

    modalVisible.value = true;
};

// 处理删除
const handleDelete = async (record) => {
    try {
        loading.value = true;
        cvaiApi.IEC61850ModelDel({ uuid: record.uuid }).then((res) => {
            if (res.code == 200) {
                message.success('删除成功');
                fetchData();
            } else {
                message.error('删除失败');
            }
        });
    } catch (error) {
        console.error('删除失败:', error);
        message.error('删除失败');
    } finally {
        loading.value = false;
    }
};

// 查看数据点表
const handleViewDataPoints = (record) => {
    // 这里实现跳转到数据点表页面
    message.info(`查看模型 ${record.name} 的数据点表`);
};

// 处理模态框确定
const handleModalOk = async () => {
    try {
        await formRef.value.validate();
        confirmLoading.value = true;

        if (isEdit.value) {
            // 编辑
            const obj = {
                uuid: currentModelId.value,
                data: { ...formState },
            };
            cvaiApi.IEC61850ModelEdit(obj).then((res) => {
                if (res.code == 200) {
                    message.success('编辑成功');
                    refreshList();
                    modalVisible.value = false;
                } else {
                    message.error('编辑失败');
                }
            });
        } else {
            // 新增
            cvaiApi.IEC61850ModelAdd(formState).then((res) => {
                if (res.code == 2002) {
                    message.success('新建成功');
                    refreshList();
                    modalVisible.value = false;
                } else {
                    message.error('新建失败');
                }
            });
        }

        modalVisible.value = false;
        fetchData();
    } catch (error) {
        console.error('操作失败:', error);
        if (error.response && error.response.data) {
            message.error(error.response.data.message || '操作失败');
        } else if (!error.errorFields) {
            message.error('操作失败');
        }
    } finally {
        confirmLoading.value = false;
    }
};
//组态模型options
const modelOptions = ref([]);
const pageOptions = ref([]);
function getDisplayModelListOptions() {
    cvaiApi.getDisplayModelList().then((res) => {
        modelOptions.value = res.list;
    });
}
//联动调用接口获取List
const changeConfigUid = (value) => {
    cvaiApi.getMonitorDetail({ muid: value }).then((res) => {
        if (res.code == 0) {
            pageOptions.value = res.layer;
        }
    });
};

// 重置表单
const resetForm = () => {
    formRef.value?.resetFields();
    currentModelId.value = null;
    Object.assign(formState, {
        name: '',
        dec: '',
        type: 350,
        gatherNumber: 0,
        configUid: '',
        PageUUID: '',
    });
};
</script>

<style scoped>
.modbus-model-management {
    padding: 20px;
    background: #fff;
}

.table-operations {
    margin-bottom: 16px;
}

.table-operations>button {
    margin-right: 8px;
}
</style>